<template>
  <div style="padding: 10px; width: 100%">
    <!--    搜索模塊-->
    <div style="margin: 10px 0; width: 800px;">
      <el-input
          placeholder="请输入学生学号"
          v-model="selectFrom.studentId"
          style="width: 200px"
      >
        <template #append>
          <el-button icon="el-icon-search" @click="load" @keyup.enter="load"></el-button>
        </template>
      </el-input>
      <el-input
          placeholder="请输入学生姓名"
          v-model="selectFrom.studentName"
          style="width: 200px;margin-left: 20px"
      >
        <template #append>
          <el-button icon="el-icon-search" @click="searchByName()" @keyup.enter="searchByName()"></el-button>
        </template>
      </el-input>
      <span style="margin-left: 20px">班级：</span>
      <el-select
          v-model="selectFrom.className"
          placeholder="请选择"
          style="width: 100px"
          clearable
          @change="selectClass()"
      >
        <el-option
            v-for="item in clazz"
            :key="item.value"
            :label="item.name"
            :value="item.id"
        >
        </el-option>
      </el-select>
      <i class="el-icon-refresh-right" @click="refresh()"></i>
    </div>
    <!--    新增和导出模块-->
    <div style="margin: 10px 0">
      <el-button
          @click="addVisible=true"
          size="mini"
          type="primary"
          plain
      >新增学生成绩
      </el-button>
      <el-button
          @click="outExe"
          size="mini"
          type="primary"
          plain
      >导出学生成绩
      </el-button>
    </div>
    <div>
      <el-upload
          class="upload-demo"
          ref="upload"
          action="http://localhost:8081/excel/import_excel"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :file-list="fileList"
          :auto-upload="false">
        <el-button slot="trigger" size="small" type="success" plain>选取上传文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" plain @click="submitUpload">上传文件
        </el-button>
      </el-upload>
    </div>
    <div style="margin: 10px 0; width: 500px; float: right"></div>
    <!--  表格-->
    <el-table :data="tableData" border stripe style="width: 99%" height="72vh">
      <el-table-column type="index" width="50" label="排名"/>
      <el-table-column prop="mystudents.stuId" label="学号" sortable/>
      <el-table-column prop="stuName" label="姓名"/>
      <el-table-column prop="className" label="班级"/>
      <el-table-column label="语文成绩" sortable prop="china">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px;color: green" v-if="scope.row.china>80">{{
                scope.row.china + '(优秀)'
              }}</span>
            <span style="margin-left: 10px;color: red" v-else-if="scope.row.china<60">{{
                scope.row.china + '(不合格)'
              }}</span>
            <span style="margin-left: 10px;" v-else>{{
                scope.row.china
              }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="math" label="数学成绩" sortable>
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px;color: green" v-if="scope.row.math>80">{{
                scope.row.math + '(优秀)'
              }}</span>
            <span style="margin-left: 10px;color: red" v-else-if="scope.row.math<60">{{
                scope.row.math + '(不合格)'
              }}</span>
            <span style="margin-left: 10px;" v-else>{{
                scope.row.math
              }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="eng" label="英语成绩" sortable>
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <span style="margin-left: 10px;color: green" v-if="scope.row.eng>80">{{
                scope.row.eng + '(优秀)'
              }}</span>
            <span style="margin-left: 10px;color: red" v-else-if="scope.row.eng<60">{{
                scope.row.eng + '(不合格)'
              }}</span>
            <span style="margin-left: 10px;" v-else>{{
                scope.row.eng
              }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="sum" label="总成绩" sortable/>
      <el-table-column prop="avg" label="平均成绩" sortable/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
              @click="handleEdit(scope.row,scope.index)"
              size="mini"
              type="primary"
              plain
          >修改
          </el-button>
          <el-button
              @click="deleteScore(scope.row)"
              size="mini"
              type="danger"
              plain
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      >
      </el-pagination>
    </div>
    <div>
      <el-dialog
          title="提示"
          v-model="dialogVisible"
          width="30%"
          :before-close="handleClose">
        <el-form :model="updateForm">
          <el-form-item label="语文成绩" :label-width="formLabelWidth">
            <el-input v-model="updateForm.china" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="数学成绩" :label-width="formLabelWidth">
            <el-input v-model="updateForm.math" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="英语成绩" :label-width="formLabelWidth">
            <el-input v-model="updateForm.eng" autocomplete="off"/>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="update()">确 定</el-button>
  </span>
      </el-dialog>
    </div>
    <!--新增模块-->
    <div>
      <el-dialog
          title="提示"
          v-model="addVisible"
          width="30%"
          :before-close="handleClose">
        <el-form :model="addForm">
          <el-form-item label="班级" :label-width="formLabelWidth">
            <el-select
                v-model="addForm.classId"
                placeholder="请选择"
                style="width: 100px"
                clearable
            >
              <el-option
                  v-for="item in clazz"
                  :key="item.value"
                  :label="item.name"
                  :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学号" :label-width="formLabelWidth">
            <el-input v-model="addForm.studentId" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="姓名" :label-width="formLabelWidth">
            <el-input v-model="addForm.studentName" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="语文成绩" :label-width="formLabelWidth">
            <el-input v-model="addForm.china" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="数学成绩" :label-width="formLabelWidth">
            <el-input v-model="addForm.math" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="英语成绩" :label-width="formLabelWidth">
            <el-input v-model="addForm.eng" autocomplete="off"/>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="addVisible = false">取 消</el-button>
    <el-button type="primary" @click="add()">确 定</el-button>
  </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import request from "../../utils/request";
import {export_json_to_excel} from "@/excal/Export2Excel";

export default {
  name: "List",
  data() {
    return {
      addVisible: false,
      dialogVisible: false,
      fileList: [],
      tableData: [],
      //当前页
      currentPage: 1,
      // 页大小
      pageSize: 10,
      // 总条数
      total: 0,
      tempData: [],
      // 考试id
      examInfo: {},
      // 班级下拉数据
      clazz: [],
      // 课程下拉数据
      course: [],
      excelData: [],
      scoreForm: {},
      updateForm: {
        studentId: '',
        math: 0,
        eng: 0,
        china: 0,
      },
      addForm: {
        studentId: '',
        math: 0,
        eng: 0,
        china: 0,
        classId: 0,
        studentName: '',
      },
      selectFrom: {
        className: '',
        studentId: '',
        studentName: '',
      },
      deleteFrom: {
        studentId: '',
      },
      rowId: 0,
    };
  },
  created() {
    this.getScoreById()
    //获取我们的课程
    this.getAllCourse()
    this.getAllClasses();
  },
  methods: {
    searchByName() {
      var stuId = this.selectFrom.studentName

      function findStuId(ele) {
        return ele.mystudents.stuName.includes(stuId)
      }

      this.tableData = this.tempData
      this.tableData = this.tableData.filter(findStuId)
    },
    submitUpload() {
      this.$refs.upload.submit();
      setTimeout(function () {
        window.location.reload()
      }, 3000)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    // 打开编辑框
    add() {
      request.post("/my_score/addScore", this.addForm).then(res => {
        this.addVisible = false;
        location.reload()
      })
    },
    deleteScore(row) {
      this.$confirm("你确定要删除吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.deleteFrom.studentId = JSON.parse(JSON.stringify(row)).stuId
        console.log(this.deleteFrom)
        request.post("/my_score/deleteScore", this.deleteFrom).then(res => {
          this.tableData = this.tableData.filter(item => item.stuId !== this.deleteFrom.studentId)
          this.tempData = this.tableData
        })
      }).catch(() => {
      });
    },
    handleEdit(row) {
      var tmp = JSON.parse(JSON.stringify(row));
      this.updateForm.eng = parseInt(tmp.eng)
      this.updateForm.math = parseInt(tmp.math)
      this.updateForm.china = parseInt(tmp.china)
      this.updateForm.studentId = tmp.mystudents.stuId
      this.dialogVisible = true
    },
    update() {
      request.post("/my_score/updateScore", this.updateForm).then(res => {
        console.log(res.data.data)
        window.location.reload()
        this.dialogVisible = false
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
    },
    // 导出excel表格
    outExe() {
      this.$confirm("此操作将导出excel文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            this.excelData = this.tableData; //你要导出的数据list。
            this.export2Excel();
          })
          .catch(() => {
          });
    },
    export2Excel() {
      var that = this;
      require.ensure([], () => {
        const {export_json_to_excel} = require("../../excal/Export2Excel"); //这里必须使用绝对路径，根据自己的命名和路径
        const tHeader = [
          "学号",
          "姓名",
          "班级",
          "语文成绩",
          "数学成绩",
          "英语成绩",
          "总成绩",
          "平均成绩",
        ]; // 导出的表头名
        const filterVal = [
          "stuId",
          "stuName",
          "className",
          "china",
          "math",
          "eng",
          "sum",
          "avg",
        ]; // 导出的表头字段名
        const list = that.excelData;
        // that.excelData为传入的数据
        const data = that.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, '学生成绩单'); // 导出的表格名称，根据需要自己命名
        // tHeader为导出Excel表头名称，`xxxxxx`即为导出Excel名称
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    selectClass() {
      var stuId = this.selectFrom.className

      function findStuId(ele) {
        return ele.classId === stuId
      }

      this.tableData = this.tempData
      this.tableData = this.tableData.filter(findStuId)
    },
    // 获取考试ID，年级id
    refresh() {
      this.tableData = this.tempData
      this.selectFrom = {}
    },
    getAllClasses() {
      request.get("/my_class/all").then((res) => {
        this.clazz = res.data.data
      })
    },
    getAllCourse() {
      request.get("/my_course/all").then((res) => {
        console.log('获取到的课程是')
        console.log(res.data.data)
        this.course = res.data.data
      })
    },
    getScoreById() {
      request
          .get("/my_score/getByClassId", {
            params: {
              "classId": 0
            }
          }).then((res) => {
        console.log(res.data.data)
        this.tableData = res.data.data
        for (var i = 0; i < this.tableData.length; i++) {
          var className = this.tableData[i].classId;
          var sum = this.tableData[i].math + this.tableData[i].eng + this.tableData[i].china
          this.tableData[i].sum = sum;
          this.tableData[i].stuName = this.tableData[i].mystudents.stuName
          this.tableData[i].avg = parseInt(sum / 3)
          this.tableData[i].className = '软件21' + className
        }
        this.tempData = this.tableData
        this.total = this.tableData.length
      })
    },
    // 分页查询当前考试的成绩
    load() {
      var stuId = this.selectFrom.studentId

      function findStuId(ele) {
        return ele.mystudents.stuId.includes(stuId)
      }

      this.tableData = this.tempData
      this.tableData = this.tableData.filter(findStuId)
    },
    // 查询当前考试的班级
    getClazz() {
      request.get('/clazz/findClazzByGid', {
        params: {
          gradeId: this.examInfo.gradeId
        }
      }).then((res => {
        console.log(res);
        this.clazz = res.data
      }))
    },
    //改变当前每页的个数触发(分页放到前端去做)
    handleSizeChange(pageSize) {
      this.tableData = this.tempData
      this.pageSize = pageSize;
      this.changeData();
    },
    changeData() {
      this.tableData = this.tableData.slice(0, this.pageSize)
    },
    changeData2() {
      this.tableData = this.tableData.slice(this.pageSize * (this.currentPage - 1),
          this.currentPage * this.pageSize)
    },
    //改变当前页码触发
    handleCurrentChange(pageNum) {
      this.tableData = this.tempData
      this.currentPage = pageNum;
      this.changeData2();
    },
  },
};
</script>
<style>
.count {
  color: #999;
  margin-top: 10px;
  font-size: 15px;
  font-weight: bold;
  text-align: center;
}
</style>